package controllers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.FileUtils;

import play.mvc.Controller;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;

public class Picture extends Controller {
	private static final String PIC_PATH="D:\\bbs\\pic\\";
	public static final String PIC_URL_PREFIX = "/pic/";
	public static Result upLoad() {
		MultipartFormData body = request().body().asMultipartFormData();
		FilePart picture = body.getFile("picture");
		if (picture != null) {
			String fileName = String.valueOf((new Date()).getTime());
			String contentType = picture.getContentType(); 
			String extension = getExtensionName(picture.getFilename());
			File src = picture.getFile();
			String dstFileName = fileName + "." + extension;
			File dest = new File(PIC_PATH + dstFileName);
			try {
				FileUtils.moveFile(src, dest);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return ok("error " + e.toString());
			}
			return ok(PIC_URL_PREFIX + dstFileName);
		} else {
			flash("error", "Missing file");
			return ok("error " + "未收到文件内容");    
		}
	}
	
	public static Result get(String id) {
		return ok(new java.io.File(PIC_PATH+id));
	}
	
	private static String getExtensionName(String filename) {   
        if ((filename != null) && (filename.length() > 0)) {   
            int dot = filename.lastIndexOf('.');   
            if ((dot >-1) && (dot < (filename.length() - 1))) {   
                return filename.substring(dot + 1);   
            }   
        }   
        return filename;   
    }   
}
